package com.qingke.easyjava.springhibernate.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingke.easyjava.springhibernate.bean.User;
import com.qingke.easyjava.springhibernate.service.ExpenseService;


public class RegisterServlet extends HttpServlet {
       

    @Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     WebApplicationContext wac =WebApplicationContextUtils.
	    getRequiredWebApplicationContext(getServletContext());
	     
	     ExpenseService service =wac.getBean(ExpenseService.class);
	     
	     request.setCharacterEncoding("UTF-8");
	     request.setCharacterEncoding("UTf-8");
	     
	     
	     String username=request.getParameter("username");
	     if(service.isUsernameExists(username)){
	    	 response.getWriter().println("<script>alert('username is exists!');window.histroy.back(-1);</script>");
	     }
	     String password =request.getParameter("password");
	     String nickname =request.getParameter("nickname");
	     
	     User user=new User();
	     user.setUsername(username);
	     user.setPassword(password);
	     user.setName(nickname);
	     service.insertUser(user);
	     response.getWriter().println("<script>alert('register success!');window.location.href='login.html';</script>");    
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
